package com.springapp.mvc;

//import org.apache.logging.log4j.*;
import com.springapp.jgit.App;
import com.springapp.sqlite.ConfigModel;
import com.springapp.symm.service.GithubManager;
import com.springapp.utils.*;
import org.springframework.beans.*;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.*;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;
import javax.servlet.ServletContext;
import javax.tools.Tool;
import java.io.File;
import java.util.List;

@Component
public class StartupListener implements ApplicationContextAware, ServletContextAware,
        InitializingBean, ApplicationListener<ContextRefreshedEvent> {

    //protected Logger logger = LogManager.getLogger();

    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        System.out.println("1 => StartupListener.setApplicationContext");
    }

    @Override
    public void setServletContext(ServletContext context) {
        System.out.println("2 => StartupListener.setServletContext");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("3 => StartupListener.afterPropertiesSet");
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent evt) {

        System.out.println("4.1 => MyApplicationListener.onApplicationEvent");
        //GlobalUtils g = new GlobalUtils();
        //g.init();
        if (evt.getApplicationContext().getParent() == null) {
            System.out.println("4.2 => MyApplicationListener.onApplicationEvent");
            //github dowload
            //new GithubManager().dowloadFiles();

            /*SqliteUtils.createDb();
            SqliteUtils.createTable();
            SqliteUtils.insert();
            GlobalUtils.ConfigModelList  = SqliteUtils.select();*/

           /* for(int i=0;i<GlobalUtils.ConfigModelList .size();i++){

                ConfigModel cm = GlobalUtils.ConfigModelList.get(i);
                GlobalUtils.ConfigModelGlobal = cm;
                try {
                    if( FileTools.judgeIsFileExist(cm.getBasePath(),false) ){
                        FileTools.deleteDirectory(cm.getBasePath());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                ;
                new App().cloneRepository(cm.getGithubDowloadPath(),cm.getBasePath());
            }*/

           //判断是否存在
            if(FileTools.judgeIsFolderExist(GlobalUtils.getBasePath(),false)){
                FileTools.deleteDirectory(GlobalUtils.getBasePath());
            }
            new App().cloneRepository(GlobalUtils.getGithubDowloadPath(), GlobalUtils.getBasePath());
        }
    }

}